<template>
  <div ref="videoPlayerBox" class="component">
    <video class="videoPlayer video-js"></video>
  </div>
</template>
<script>
import videojs from "video.js"
import "video.js/dist/video-js.min.css"
// import 'videojs-contrib-hls'
// import 'videojs-flvjs-es6'
import "videojs-flash"
import SWF_URL from "videojs-swf/dist/video-js.swf"

export default {
  data() {
    return {
      player: null,
    }
  },
  mounted() {
    this.initPlayer()
  },
  beforeDestroy() {
    this.disposePlayer()
  },
  methods: {
    // 初始化播放器
    initPlayer() {
      this.$nextTick(() => {
        let playerOption = {
          preload: "auto", // 预加载
          autoplay: true, // 自动播放
          controls: true,
          techOrder: ["flash"], // 这里的顺序一定要 'flvjs' 在 'flash' 前面，要不然 flv 格式的就无法播放了
          // 如果报 app.js:242798 Uncaught TypeError: this.el_.vjs_getProperty is not a function 错误，只保留 'flash' 就不报错了
          // 报错 The "flash" tech is undefined. Skipped browser support check for that tech. 可以查看 videojs-flash 里面 node_modules 查看需要的 video.js 的版本，然后修改video.js的版本就可以了
          flash: {
            hls: { withCredentials: false },
            swf: SWF_URL, // 引入静态文件swf
          },
          flvjs: {
            mediaDataSource: {
              cors: true,
              withCredentials: false,
            },
          },
          sources: [
            {
              src: "rtmp://81.69.252.51:1933/live/8782",
              type: "rtmp/flv",
            },
          ],
        }

        this.player = videojs(
          this.$el.querySelector(".videoPlayer"),
          playerOption,
          function onPlayerReady() {
            console.log("onPlayerReady", this)
          }
        )
      })
    },
    // 重新加载播放器
    loadPlayer() {
      this.$refs.videoPlayerBox.innerHTML = `<video class="videoPlayer video-js"></video>`
      this.$nextTick(() => {
        this.initPlayer()
      })
    },
    // 销毁播放器
    disposePlayer() {
      if (this.player) {
        this.player.dispose()
      }
    },
  },
}
</script>
